package com.xs.aifitnessagent.exp;

import cn.dev33.satoken.exception.NotLoginException;
import com.xs.aifitnessagent.enums.ReturnCodeEnum;
import com.xs.aifitnessagent.resp.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 *
 * @author lambor
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理Sa-Token未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public ResponseEntity<ResultData<String>> handleNotLoginException(NotLoginException e) {
        log.warn("用户未登录或token已失效: {}", e.getMessage());
        
        ResultData<String> resultData = ResultData.fail(
            ReturnCodeEnum.NOT_LOGIN.getCode(),
            ReturnCodeEnum.NOT_LOGIN.getMessage()
        );
        
        // 返回401状态码，表示需要重新认证
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resultData);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultData<String> handleBusinessException(BusinessException e) {
        log.warn("业务异常: code={}, message={}", e.getCode(), e.getMessage());
        return ResultData.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理其他运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultData<String> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常: {}", e.getMessage(), e);
        return ResultData.fail(
            ReturnCodeEnum.RC500.getCode(),
            "系统异常，请稍后重试"
        );
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultData<String> handleException(Exception e) {
        log.error("未知异常: {}", e.getMessage(), e);
        return ResultData.fail(
            ReturnCodeEnum.RC500.getCode(),
            "系统异常，请稍后重试"
        );
    }
} 